#!/bin/bash

# 安装 opentsdb
yum install http://soft.hc-yun.com/base/software/opentsdb-2.4.0.noarch.rpm

# 获取当前IP地址
host_if=$(/usr/sbin/ip route|grep default|cut -d' ' -f5)
host_ip=$(/usr/sbin/ip a|grep "$host_if$"|awk '{print $2}'|cut -d'/' -f1)

# 创建配置文件
zookeeper=${1:-$host_ip}
cat > /etc/opentsdb/opentsdb.conf <<EOF
tsd.core.preload_uid_cache = true
tsd.core.auto_create_metrics = true
tsd.storage.enable_appends = true
tsd.core.enable_ui = true
tsd.core.enable_api = true
tsd.network.port = 14242
tsd.http.staticroot = /usr/share/opentsdb/static
tsd.http.cachedir = /home/opentsdb
tsd.http.request.enable_chunked = true
tsd.http.request.max_chunk = 65535
tsd.storage.hbase.zk_quorum = $zookeeper:2181
tsd.query.timeout = 0
tsd.query.filter.expansion_limit = 65535
tsd.network.keep_alive = true
tsd.network.backlog = 3072
tsd.storage.fix_duplicates = true

tsd.core.tag.allow_specialchars = ()
tsd.storage.hbase.data_table = tsdb
tsd.storage.hbase.zk_basedir = /hbase
tsd.query.skip_unresolved_tagvs = true
EOF

# 创建服务启动/关闭脚本
cat > /etc/opentsdb/opentsdb.sh <<'EOF'
#!/bin/bash

ARG=$1
source /etc/profile
start(){
    /usr/bin/tsdb tsd --config /etc/opentsdb/opentsdb.conf > /dev/null 2>&1 &
}

stop(){
    jps | grep TSDMain | awk '{print $1}' | xargs kill > /dev/null 2>&1
}

case "$ARG" in
    stop)   stop
    ;;
    start)   start
    ;;
    *)   echo "$0 {start|stop}"
    ;;
esac
EOF

chmod +x /etc/opentsdb/opentsdb.sh

# 创建服务管理脚本
source /etc/profile
cat > /usr/lib/systemd/system/opentsdb.service <<EOF
[Unit]
Description=OpenTSDB
After=network-online.target
# Wants=hbase.service

[Service]
TimeoutSec=10
Type=forking
Environment=JAVA_HOME=$JAVA_HOME
Environment='JVMARGS=-Xmx6000m -DLOG_FILE=/var/log/opentsdb/%p_%i.log -DQUERY_LOG=/var/log/opentsdb/%p_%i_queries.log -XX:+ExitOnOutOfMemoryError -enableassertions -enablesystemassertions'
ExecStart=/etc/opentsdb/opentsdb.sh start
ExecStop=/etc/opentsdb/opentsdb.sh stop

[Install]
WantedBy=multi-user.target
EOF

# 跟随系统启动
systemctl daemon-reload
systemctl enable opentsdb

# opentsdb 初始化
echo """
----------------------------------------------------------------
                   opentsdb 初始化

    cp /usr/share/opentsdb/tools/create_table.sh /tmp/create_table.sh
    sed -i 's#\$TSDB_TTL#2147483647#' /tmp/create_table.sh
    env COMPRESSION=none HBASE_HOME=/opt/cloudera/parcels/CDH-5.16.1-1.cdh5.16.1.p0.3/lib/hbase /tmp/create_table.sh

    systemctl start opentsdb
"""